package com.example.springboot.service.impl;

import com.example.springboot.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.keyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.keySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;


    public String uploadFile(MultipartFile file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(bucketName, fileName, inputStream);
        ossClient.shutdown();
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
